package com.sky.controller.admin;

import com.sky.service.impl.TestServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @Author : xiongke
 * @Description:
 * @Date: 2024/9/23
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class TestThreadPoolController {

    @Resource
    TestServiceImpl testService;

    @Resource
    ThreadPoolTaskExecutor executor;

    @GetMapping("/1")
    public List getUser(){
        long start = System.currentTimeMillis();
        List age = testService.getAge();
        List name = testService.getName();
        List sex = testService.getSex();
        ArrayList<Object> objects = new ArrayList<>();
        objects.add(age);
        objects.add(name);
        objects.add(sex);
        System.out.println("list：" + objects);
        System.out.println("shijian ： " + (System.currentTimeMillis() - start));
        return objects;
    }

    @GetMapping("/2")
    public List getUserByThreadPool() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();

        ArrayList<Object> objects = new ArrayList<>();
        CompletableFuture<Void> ageFuture = CompletableFuture.runAsync(() -> {
            List age = testService.getAge();
            objects.add(age);
        }, executor);

        CompletableFuture<Void> nameFuture = CompletableFuture.runAsync(() -> {
            List name = testService.getName();
            objects.add(name);
        }, executor);

        CompletableFuture<Void> sexFuture = CompletableFuture.runAsync(() -> {
            List sex = testService.getSex();
            objects.add(sex);
        }, executor);

        CompletableFuture.allOf(ageFuture,nameFuture,sexFuture).get();
        System.out.println("List2:{}" + objects);
        System.out.println("时间：" + (System.currentTimeMillis() - start));
        return objects;
    }


}
